<?php

namespace app\store\service;

use app\store\model\PaymentConfig;

class PaymentConfigService
{

    public static function findPaymentConfig()
    {
        $store_id = session('store_id');
        $paymentConfig = PaymentConfig::withOutField('create_time,update_time')
                                        ->limit(2)->where('store_id',$store_id)->select();

        if ($paymentConfig->isEmpty()){
            return [];
        }

        $arr = [];
        foreach ($paymentConfig->toArray() as  $v){
            $v['config'] = json_decode($v['config'],true);
            if ($v['type']==1){
                $filenamekey = app_path() . '/ssl/' . md5($store_id) .'/apiclient_key.pem';
                $filenameCer = app_path() . '/ssl/' . md5($store_id) .'/apiclient_cert.pem';
                $v['config']['ssl_key'] = file_get_contents($filenamekey);
                $v['config']['ssl_cer'] = file_get_contents($filenameCer);
            }
            $arr[$v['type']] = $v;
        }
    
        return  $arr;
    }

    public static function savePaymentConfig($data)
    {

        $data['store_id'] = session('store_id');

        $config = [];

        $config['appid'] = $data['appid'];
        if ($data['type'] ==1){
            $filenames = static::saveCertPath($data['store_id'],$data['ssl_key'],$data['ssl_cer']);
            list($ssl_key,$ssl_cer) = $filenames;
            $config['mch_id'] = $data['mch_id'];
            $config['mch_key'] = $data['mch_key'];
            $config['ssl_key'] = $ssl_key;
            $config['ssl_cer'] = $ssl_cer;

        }

        if ($data['type'] == 2){
            $config['private_key'] = $data['private_key'];
            $config['public_key'] = $data['public_key'];
        }

        $data['config'] = json_encode($config);


        $payment = PaymentConfig::create($data,[],true);

        return $payment['id'];
    }

    public static function saveCertPath($store_id,$ssl_key,$ssl_cer)
    {
        $dir = app_path() . 'ssl/' . md5($store_id);

        if (!is_dir($dir)){
            mkdir($dir);
        }

        $filenamekey = $dir .'/apiclient_key.pem';
        $filenameCer = $dir .'/apiclient_cert.pem';



        if (!file_exists($filenamekey)){
            touch($filenamekey);
        }

        if (!file_exists($filenameCer)){
            touch($filenameCer);
        }

        file_put_contents($filenamekey,$ssl_key);
        file_put_contents($filenameCer,$ssl_cer);

        return [$filenamekey,$filenameCer];
    }



    
}